package com.vehiclesecure.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/test-jwt")
public class JwtTestController {

    private final JwtService jwtService;
// 由于 userDetailsService 未被使用，移除该字段

    @Autowired
    public JwtTestController(JwtService jwtService, UserDetailsService userDetailsService) {
        this.jwtService = jwtService;
// 由于 userDetailsService 未被使用，且根据注释提示要移除该字段，因此移除该赋值语句
    }

    @GetMapping("/generate-and-verify")
    public Map<String, Object> generateAndVerifyToken() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 创建一个测试用户
            UserDetails testUser = User.withUsername("testuser")
                    .password("password")
                    .roles("USER")
                    .build();
            
            // 生成令牌
            String token = jwtService.generateToken(testUser);
            response.put("generatedToken", token);
            
            // 验证令牌
            boolean isValid = jwtService.isTokenValid(token, testUser);
            response.put("isValid", isValid);
            
            // 提取用户名进行验证
            String username = jwtService.extractUsername(token);
            response.put("extractedUsername", username);
            
            response.put("message", "JWT test completed successfully");
            response.put("success", true);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            response.put("errorType", e.getClass().getName());
        }
        
        return response;
    }
}